package com.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot.entity.SecurityUser;
import com.example.springboot.entity.Users;
import com.example.springboot.mapper.UsersMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service
public class UserService implements UserDetailsService {

    @Resource
    UsersMapper usersMapper;

    /**
     * 从数据库根据账号查询（实际应该是账号密码）
     * @default
    **/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过账号查询，这里要求账号唯一
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("name",username);
        Users users = usersMapper.selectOne(wrapper);
        // 对象为空，登录失败
        if(users == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 设置用户
        SecurityUser securityUser = new SecurityUser(users);
        // 放权限进去
        securityUser.setPermissionValueList(Arrays.asList("admin"));
        return securityUser;
    }

}
